package com.jvm123.blog.service

import com.jvm123.blog.dao.PostPageRepo
import com.jvm123.blog.dao.PostRepos
import com.jvm123.blog.dao.TermRepos
import com.jvm123.blog.entity.Post
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service

import java.util.function.Consumer
import java.util.function.Function

/**
 *
 * @author yawn http://jvm123.com
 *     2019/10/22 14:53
 */
@Service
class PostServiceImpl implements PostService {

    @Autowired
    PostRepos postRepos
    @Autowired
    TermRepos termRepos
    @Autowired
    TermService termService
    @Autowired
    PostPageRepo postPageRepo

    @Override
    Post findOne(long id) {
        Optional<Post> postOptional = postRepos.findById(id)
        if (postOptional.isPresent()) {
            return postOptional.get()
        }
        null
    }

    @Override
    List<Post> findByType(String type) {
        postRepos.findByPostType(type)
    }

    @Override
    List<Post> findTop() {
        List<Post> list = postRepos.findTop36ByPostType("post")
        addTags(list)
        list
    }

    @Override
    Post findPostWithTags(long id) {
        Post post = findOne(id)
        addTags(post)
        post
    }

    @Override
    List<Post> findByTag(String tag) {
        List<Long> postIds = termService.findPostIdByTag(tag)
        Jdk8Utils.convert(postIds*.toLong(), new Function<Long, Post>() {
            @Override
            Post apply(Long postId) {
                Post post = findOne(postId)
                addTags(post)
                post
            }
        })
    }

    @Override
    List<Post> findByCategory(String category) {
        List<Long> postIds = termService.findPostIdByCategory(category)
        Jdk8Utils.convert(postIds*.toLong(), new Function<Long, Post>() {
            @Override
            Post apply(Long postId) {
                Post post = findOne(postId)
                addTags(post)
                post
            }
        })
    }

    @Override
    List<Post> batch(long offset) {
        Page<Post> postPage = postPageRepo.findByIdAfter(offset, PageRequest.of(0, 10))
        postPage.toList()
    }

    @Override
    List<Post> batch(int page, int size) {
        Page<Post> postPage = postPageRepo.findAll(PageRequest.of(page, size))
        postPage.toList()
    }

    def addTags(List<Post> list) {
        if (list == null) {
            return
        }
        list.forEach(new Consumer<Post>() {
            @Override
            void accept(Post post) {
                addTags(post)
            }
        })
    }

    def addTags(Post post) {
        if (post != null) {
            post.categorys = termRepos.findByPostIdAndTaxonomy(post.id, "category")
            post.tags = termRepos.findByPostIdAndTaxonomy(post.id, "post_tag")
        }
    }


}
